# -*- coding: UTF-8 -*-
from django.forms import ModelForm
from menu.models import  MyUserMenu,Menu
from django import forms
from django.contrib.auth.models import User

#定义Node的Form,Form名字为 模式名+Form
class MenuForm(ModelForm):
    def clean_text(self):
        text = self.cleaned_data['text']
        if 'text' in self.changed_data:

            text=Menu.objects.filter(text=text) or None
            if text:
                raise forms.ValidationError('菜单名%s已经存在' %text)
        return text


    templist=[('','')]
    for key,value in Menu.objects.filter(parent_id=0).values_list('id','text'):
        templist.append((key,value))

    text =forms.CharField(label='菜单名')
    #parent_id=forms.ModelChoiceField(label='父ID',queryset=Menu.objects.filter(parent_id=0),required=False)
    parent_id = forms.ChoiceField(label='父ID', choices=templist,required=False)
    namespace=forms.CharField(label='APP名')
    url_name=forms.CharField(label='ViewName')
    addition=forms.CharField(label='附加参数',required=False)



    class Meta:
        model= Menu
        fields=['text','parent_id','namespace','url_name']

class Menu_Search_Form(forms.Form):



    text =forms.CharField(label='菜单名',required=False)
    parent_id=forms.ModelChoiceField(label='父ID',queryset=Menu.objects.filter(parent_id=0))
    namespace =forms.CharField(label='APP名',required=False)
    url_name=forms.CharField(label='APP名',required=False)
    #class Meta:
    #    model = Menu
    #    exclude=['addition','is_system','checked']


class MyUserMenu_Form(forms.Form):
    def __init__(self, *arg, **kwargs):
        super(MyUserMenu_Form, self).__init__(*arg, **kwargs)
        querys=Menu.objects.filter(parent_id=0)
        self.fields['user']=forms.ModelChoiceField(label="用户名",queryset=User.objects.all())
        for var in querys:
            key="checkbox_menu_%s" %var.id
            self.fields[key] = forms.MultipleChoiceField(label=var.text,required=False,
                                                        choices=Menu.objects.filter(parent_id=var.id).values_list("id","text"),
                                                        widget=forms.CheckboxSelectMultiple)









